import 'package:flutter_module/common/base/base_page.dart';
import 'package:flutter_module/common/http/http.dart';
import 'package:flutter_module/common/http/http_error.dart';
import 'package:flutter_module/common/http/request/base_request.dart';
import 'package:flutter_module/common/utils/size_fit_utils.dart';
import 'package:flutter_module/common/utils/toast_utils.dart';

/// Create by kyluzoi
/// Date: 2021-08-10
///
/// Description:

extension IntSizeFit on int {
  double get px {
    return SizeFit.setPx(this.toDouble());
  }

  double get rpx {
    return SizeFit.setRpx(this.toDouble());
  }
}

extension UriExtension on Map<String, dynamic> {
  String map2Uri(String path) {
    return Uri.http("", path, this).toString().substring(4);
  }
}

extension MapExtension<K, V> on Map<K, V> {
  Map<K, V> operator +(Map<K, V>? map) {
    if (map != null) {
      this.addAll(map);
    }
    return this;
  }
}

extension Request on BaseRequest {
  void request(BaseState? state, Function(Map<String, dynamic>) success,
      {Function(NetWorkBaseError)? error, showToast = true}) async {
    try {
      var result = await fire(state, showToast: showToast);
      success(result);
    } catch (e) {
      if (e is NetWorkBaseError && error != null) {
        error(e);
      }
    }
  }

  Future fire(BaseState? state, {showToast = true}) async {
    try {
      var result = await YiHttp.getInstance().request(this);
      if (state != null && state.isDispose) return;
      print("networkSuccess:$result");
      return Future.value(result);
    } catch (e) {
      if (state != null && state.isDispose) return;

      if (showToast) {
        // 这里弹出错误 Toast  e.toString() 或者  e.message
        if (e is NetWorkBaseError) {
          print("is NetworkBaseError");
          ToastUtils().showText(e.message);
        } else {
          ToastUtils().showText(e.toString());
        }
      }

      print('networkerror:${e.toString()}');
      return Future.error(e);
    }
  }
}
